//
//  HomeViewController.m
//  WuJieLive
//
//  Created by iMac on 2017/10/20.
//  Copyright © 2017年 zhk. All rights reserved.
//

#import "HomeViewController.h"
#import "ScanViewController.h"
#import "LBXScanViewStyle.h"
#import "MessageViewController.h"
#import "BuyTodayCell.h"
#import "RecommendCell.h"
#import "HomeLastCell.h"
#import "GoodCategoryController.h"
#import "SearchActionView.h"
#import "RecommendModel.h"
#import "ActivesModel.h"
#import "BulletinsModel.h"
#import "GoodsDetailController.h"
#import "GoodsListEntity.h"


@interface HomeViewController ()
<
SDCycleScrollViewDelegate,
UITableViewDelegate,
UITableViewDataSource,
BaseViewDelegate
>

@property (nonatomic , strong) NSMutableArray * imageArray;
@property (nonatomic , strong) NSMutableArray * urlArray;

@property (nonatomic , strong) NSMutableArray * bulletinsArray;

@property (nonatomic , strong) NSMutableArray * activesArray;

@property (nonatomic , strong) NSMutableArray * recommendArray;

@property (nonatomic , strong) NSMutableArray * boutiqueArray;

@property (nonatomic , strong) UICollectionView * collectionView;
@property (nonatomic , strong) UIView * headerView;
@property (nonatomic , strong) UITableView * tableView;
@property (strong, nonatomic)SearchActionView *searchView;

@property (nonatomic , strong) SDCycleScrollView * cycleView;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setBarTintColor:MainColor];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.hidesBottomBarWhenPushed = NO;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
}

- (void)setNavi
{
    self.userToken = @"85d1df107821df99e6b9c0f0249caebfa29ab1c8a683f19d251bbb513cdf";
    self.isLogin = YES;
    [self.leftBtn setImage:[[UIImage imageNamed:@"icon_nav_扫描_白"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    [self.rightBtn setImage:[[UIImage imageNamed:@"icon_nav_消息_白"] imageWithRenderingMode:(UIImageRenderingModeAlwaysOriginal)] forState:(UIControlStateNormal)];
    self.navigationItem.titleView = self.searchView;
}

- (void)setData
{
    self.imageArray = [NSMutableArray array];
    self.urlArray = [NSMutableArray array];
    self.bulletinsArray = [NSMutableArray array];
    self.activesArray = [NSMutableArray array];
    self.recommendArray = [NSMutableArray array];
    self.boutiqueArray = [NSMutableArray array];
    [self requestData];
    [self requestBoutique];
}

- (void)requestData
{
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@index/index",BaseUrl] para:nil success:^(BOOL isSuccess, id responseObject) {
        if (isSuccess) {
            if ([responseObject[@"data"][@"banners"] isKindOfClass:[NSArray class]]) {
                
                for (int i = 0; i < [responseObject[@"data"][@"banners"] count]; i ++) {
                    [self.imageArray addObject:responseObject[@"data"][@"banners"][i][@"banner_img"]];
                    [self.urlArray addObject:responseObject[@"data"][@"banners"][i][@"jumpurl"]];
                }
                self.cycleView.imageURLStringsGroup = self.imageArray;
                
                for (int i = 0; i < [responseObject[@"data"][@"bulletins"] count]; i ++) {
                    BulletinsModel * model = [BulletinsModel new];
                    [model setValuesForKeysWithDictionary:responseObject[@"data"][@"bulletins"][i]];
                    [self.bulletinsArray addObject:model];
                }
                
                for (int i = 0 ; i < [responseObject[@"data"][@"actives"] count]; i ++) {
                    ActivesModel * model = [ActivesModel new];
                    [model setValuesForKeysWithDictionary:responseObject[@"data"][@"actives"][i]];
                    [self.activesArray addObject:model];
                }
                for (int i = 0; i < [responseObject[@"data"][@"recommends"] count]; i ++) {
                    RecommendModel * model = [RecommendModel new];
                    [model setValuesForKeysWithDictionary:responseObject[@"data"][@"recommends"][i]];
                    [self.recommendArray addObject:model];
                }
            }
            [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)requestBoutique
{
    [HTTPTool POSTForm:[NSString stringWithFormat:@"%@index/index-boutique",BaseUrl] para:nil success:^(BOOL isSuccess, id responseObject) {
        if (isSuccess) {
            for (int i = 0; i < [responseObject[@"data"] count]; i ++) {
                GoodsListEntity * model = [GoodsListEntity new];
                [model setValuesForKeysWithDictionary:responseObject[@"data"][i]];
                [self.boutiqueArray addObject:model];
            }
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:(UITableViewRowAnimationNone)];
        }
    } failure:^(NSError *error) {
        
    }];
}

- (void)setUI
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 - 44) style:(UITableViewStyleGrouped)];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"BuyTodayCell" bundle:nil] forCellReuseIdentifier:@"cell1"];
    [self.tableView registerNib:[UINib nibWithNibName:@"RecommendCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeLastCell" bundle:nil] forCellReuseIdentifier:@"cell3"];
    
    self.cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, kScreenWidth, 200) delegate:self placeholderImage:nil];
    
    [self.headerView addSubview:self.cycleView];
    self.cycleView.autoScrollTimeInterval = 3;
    self.cycleView.delegate = self;
    
    UIView * btnBgView = [[UIView alloc]init];
    [self.headerView addSubview:btnBgView];
    [btnBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.offset(0);
        make.top.equalTo(self.cycleView.mas_bottom);
        make.height.offset(100);
    }];
    
    UIView * lineView = [[UIView alloc]init];
    [btnBgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(btnBgView);
        make.bottom.offset(-1);
        make.height.offset(0.5);
    }];
    lineView.backgroundColor = TextLessImportColor;
    
    NSArray * titleArray = @[@"0元购",@"兑换大厅",@"商品分类"];
    NSArray * imageArray = @[@"icon_home_秒秒购",@"icon_home_兑换大厅",@"icon_home_商品分类"];
    for (int i = 0; i < 3; i ++) {
        HKButton * btn = [[HKButton alloc]init];
        [btnBgView addSubview:btn];
        btn.tag = 2000 + i;
        [btn setImage:Image(imageArray[i]) forState:(UIControlStateNormal)];
        [btn setTitle:titleArray[i] forState:(UIControlStateNormal)];
        [btn addTarget:self action:@selector(headerBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        [btn setTitleColor:TextLessImportColor forState:(UIControlStateNormal)];
        CGSize btnSize = CGSizeMake(45, 60);
        CGFloat space = (kScreenWidth - 80 - 3 * 45) / 2;
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(40 + i * (space + btnSize.width));
            make.top.offset(30);
            make.size.mas_offset(btnSize);
        }];
    }
    
    TXScrollLabelView * scrollLabelView = [[TXScrollLabelView alloc]initWithTitle:@"每次抽拉，犹如电流经过全身" type:(TXScrollLabelViewTypeUpDown) velocity:3 options:(UIViewAnimationOptionTransitionNone) inset:UIEdgeInsetsZero];
    scrollLabelView.backgroundColor = [UIColor clearColor];
    scrollLabelView.scrollTitleColor = TextAssistColor;
    scrollLabelView.font = FontSize(13);
    scrollLabelView.textAlignment = NSTextAlignmentCenter;
    scrollLabelView.frame = CGRectMake(50, 300, kScreenWidth - 80, 50);
    [self.headerView addSubview:scrollLabelView];
    [scrollLabelView beginScrolling];
    
    UIImageView * leftImage = [[UIImageView alloc]init];
    [self.headerView addSubview:leftImage];
    [leftImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(15);
        make.top.offset(320);
        make.size.mas_offset(CGSizeMake(12, 12));
    }];
    leftImage.image = Image(@"icon_通知");
    
    UIImageView * rightImage = [[UIImageView alloc]init];
    [self.headerView addSubview:rightImage];
    [rightImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-15);
        make.top.offset(320);
        make.size.mas_offset(CGSizeMake(9, 12));
    }];
    rightImage.image = Image(@"icon_close");
    
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

}


#pragma mark tableviewDelegate DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        BuyTodayCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell1" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.activesArray.count > 0) {
            [cell bindDataWithModelArray:self.activesArray];
        }
        return cell;
        
    }else if (indexPath.section == 1){
        RecommendCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.headerBtn.tag = 1000 + indexPath.row;
        [cell.headerBtn addTarget:self action:@selector(headerAction:) forControlEvents:(UIControlEventTouchUpInside)];
        cell.pushGoodsBlock = ^(NSString *goodsID) {
            GoodsDetailController * vc = [[GoodsDetailController alloc]init];
            vc.goodsID = goodsID;
            [self.navigationController pushViewController:vc animated:YES];
        };
        if (self.recommendArray.count > indexPath.row) {
            RecommendModel * model = self.recommendArray[indexPath.row];
            cell.titleLabel.text = model.title;
            [cell.headerBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:model.banner_img] forState:UIControlStateNormal];
            if (model.goods.count >= 4) {
                cell.dataArray = model.goods;
                [cell.collectionView reloadData];
            }
        }
        return cell;
    }else
    {
        HomeLastCell * cell = [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.boutiqueArray;
        [cell.collectionView reloadData];
        return cell;
    }
    return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 2;
    }else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 210;
    }else if (indexPath.section == 1){
        return 400;
    }else
    {
        return 330;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else if (section == 1)
    {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        label.text = @"专/题/推/荐";
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        return label;
    }else
    {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
        label.text = @"精/品/推/荐";
        label.textAlignment = NSTextAlignmentCenter;
        label.backgroundColor = [UIColor whiteColor];
        return label;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }else if (section == 1){
        return 50;
    }else
    {
        return 50;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
        view.backgroundColor = [UIColor clearColor];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, kScreenWidth, 20)];
        [view addSubview:label];
        label.backgroundColor = [UIColor clearColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = TextLessImportColor;
        label.font = FontSize(13);
        label.text = @"————亲，我是有底线的————";
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 50;
}

#pragma mark -- Custom Delegate

- (void)viewActionWithView:(UIView *)view tag:(NSInteger)tag data:(id)data {
    if ([view isKindOfClass:[SearchActionView class]]) {
        SearchViewController * vc = [[SearchViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

#pragma mark 头部三个按钮的点击
- (void)headerBtnAction:(UIButton *)sender
{
    // 商品分类
    if (sender.tag == 2002) {
        GoodCategoryController * vc = [[GoodCategoryController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark 专题推荐cell头部
- (void)headerAction:(UIButton *)sender
{
//    RecommendModel * model = self.recommendArray[sender.tag - 1000];
//    NSLog(@"%@",model);
}


- (void)rightBtnAction:(UIButton *)sender
{
    MessageViewController * vc = [[MessageViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 轮播图点击
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    NSLog(@"%@",self.urlArray[index]);
}

#pragma mark 搜索方法
- (void)search
{
    SearchViewController * vc = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark 扫码
- (void)leftBtnAction:(UIButton *)sender
{
    
    ScanViewController * vc = [[ScanViewController alloc]init];
    
    LBXScanViewStyle *style = [[LBXScanViewStyle alloc]init];
    style.centerUpOffset = 60;
    style.xScanRetangleOffset = 30;
    
    if ([UIScreen mainScreen].bounds.size.height <= 480 )
    {
        //3.5inch 显示的扫码缩小
        style.centerUpOffset = 40;
        style.xScanRetangleOffset = 20;
    }
    
    style.notRecoginitonArea = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
    style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle_Inner;
    style.photoframeLineW = 2.0;
    style.photoframeAngleW = 16;
    style.photoframeAngleH = 16;
    
    style.isNeedShowRetangle = NO;
    style.anmiationStyle = LBXScanViewAnimationStyle_NetGrid;
    
    //使用的支付宝里面网格图片
    UIImage *imgFullNet = [UIImage imageNamed:@"CodeScan.bundle/qrcode_scan_full_net"];
    style.animationImage = imgFullNet;
    vc.isOpenInterestRect = YES;
    vc.style = style;
    
    [self.navigationController pushViewController:vc animated:YES];

}

- (SearchActionView *)searchView {
    if (!_searchView) {
        _searchView = [[SearchActionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 100, 30)];
        _searchView.delegate = self;
    }
    return _searchView;
}

-(UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 350)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    return _headerView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
